<?php

/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2023-04-24 13:54:59
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2023-07-28 14:15:42
 */

namespace Common;

use Common\Channels\TcpChannel;
use Common\Helpers\DebugHelper;
use Hyperf\Contract\ContainerInterface;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Request;
use Hyperf\HttpServer\Response;
use Hyperf\HttpServer\Router\DispatcherFactory;
use Hyperf\Redis\RedisFactory;
use Hyperf\WebSocketServer\Context;
use Hyperf\WebSocketServer\Sender;
use Psr\Http\Message\ServerRequestInterface;

abstract class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    public array $authOptional = [];

    /**
     * 不需要进行签名验证的方法
     * @var array
     */
    public  array $signOptional = [];


    protected int $project_id = 0;

    protected int $member_id = 0;

    /**
     * @var StdoutLoggerInterface
     */
    #[Inject]
    protected StdoutLoggerInterface $logger;


    /**
     * @var Sender
     */
    #[Inject]
    protected Sender $sender;

    /**
     * @Inject(ContainerInterface::class)
     * @var ContainerInterface
     */
    #[Inject]
    protected ContainerInterface $container;


    /**
     * @Inject(DispatcherFactory::class)
     * @var DispatcherFactory
     */
    #[Inject]
    protected DispatcherFactory $dispatcherFactory;

    /**
     * @Inject(RequestInterface::class)
     * @var Request
     */
    #[Inject]
    protected \Hyperf\HttpServer\Contract\RequestInterface $request;

    /**
     * @Inject(ResponseInterface::class)
     * @var Response
     */
    #[Inject]
    protected \Hyperf\HttpServer\Contract\ResponseInterface $response;

    /**
     * 无法正常挂载，使用上下文
     * @param $key
     * @return array|mixed
     */
    public function getContext($key): mixed
    {
        return Context::get($key);
    }



    public function writeJson($statusCode, $result, $msg,$type = 'default'): array
    {
        if ($result && is_array($result) && key_exists('code', $result)) {
            // 服务中包含了状态，直接返回
            $data = $result;
        } else {
            $data = [
                'code' => $statusCode,
                'type' => $type,
                'data' => $result,
                'message' => $msg,
            ];
        }

        return $data;
    }
}
